package com.km.wskj.itmonitor.pager.monitor;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.km.wskj.itmonitor.pager.monitor.adapter.FragmentAdapter;
import com.km.wskj.itmonitor.pager.monitor.alarm.AlarmListActivity;
import com.km.wskj.itmonitor.pager.monitor.application.AppListActivity;
import com.km.wskj.itmonitor.pager.monitor.quota.QuotaActivity;
import com.km.wskj.itmonitor.pager.monitor.database.DBListActivity;
import com.km.wskj.itmonitor.pager.monitor.dh.DhActivity;
import com.km.wskj.itmonitor.pager.monitor.fragment.AppAbilityFragment;
import com.km.wskj.itmonitor.pager.monitor.fragment.AppRunStateFragment;
import com.km.wskj.itmonitor.pager.monitor.internet.InternetListActivity;
import com.km.wskj.itmonitor.pager.monitor.itsm.ITSMActivity;
import com.km.wskj.itmonitor.pager.monitor.server.ServerListActivity;
import com.km.wskj.itmonitor.utils.StatusBarCompat;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author by Xianling.Zhou on 2017/2/9.
 */
//监控主界面
public class MonitorFragment extends LFragment implements ViewPager.OnPageChangeListener {
    //ui
    @BindView(R.id.tool_bar_right)
    ImageView mRight;
    @BindView(R.id.tool_bar_title)
    TextView mTitle;
    @BindView(R.id.container_gridview)
    LinearLayout container_gridview;
    @BindView(R.id.monitor_viewpager)
    ViewPager mViewPager;
    @BindView(R.id.ll_dot)
    LinearLayout mLldot;
    @BindView(R.id.srf_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.service_manager)
    LinearLayout serviceManager;
    @BindView(R.id.custom_service)
    LinearLayout customService;
    @BindView(R.id.operation_quality)
    LinearLayout operationQuality;
    @BindView(R.id.yj_manager)
    LinearLayout yjManager;

    /**
     * 保存点的数组
     */
    private View[] dots = new View[2];
    /**
     * 保存白色的点
     */
    private View currentDot;

    //data
    List<FuncItem> funcItems;
    private MyGridView gridView;
    private AppRunStateFragment appRunStateFragment;
    private AppAbilityFragment appAbilityFragment;
    private FragmentAdapter mFragmentAdapter;
    private List<LFragment> fragments;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_monitor, container, false);
        ButterKnife.bind(this, view);
        //沉浸shi
        StatusBarCompat.compat(getActivity(), getResources().getColor(R.color.colorWs_blue));
        mRight.setVisibility(View.VISIBLE);
        mTitle.setText("监控");
        initData();
        initFuncItems();
        initRefresh();
        return view;
    }

    private void initData() {
        mLldot.removeAllViews();
        /**
         * 初始化fragment
         */
        fragments = new ArrayList<>();
        appRunStateFragment = new AppRunStateFragment();
        appAbilityFragment = new AppAbilityFragment();

        fragments.add(appRunStateFragment);
        fragments.add(appAbilityFragment);

        for (int i = 0; i < fragments.size(); i++) {
            createDot(i);
        }
        /**
         * 初始化adapter
         */
        mFragmentAdapter = new FragmentAdapter(getChildFragmentManager(), fragments);
        mViewPager.setAdapter(mFragmentAdapter);
        mViewPager.setOnPageChangeListener(this);
        //手动设置小圆点是第一个
        change(0);
    }

    private void initRefresh() {
        // 不能在onCreate中设置，这个表示当前是刷新状态，如果一进来就是刷新状态，SwipeRefreshLayout会屏蔽掉下拉事件
        //swipeRefreshLayout.setRefreshing(true);
        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorWs_blue, R.color.colorPrimary, R.color.colorPrimaryDark);
        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 开始刷新，设置当前为刷新状态
                //swipeRefreshLayout.setRefreshing(true);
                // 加载完数据设置为不刷新状态，将下拉进度收起来
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        normalToasty("刷新成功");
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        container_gridview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                container_gridview.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
    }


    private void initFuncItems() {
        funcItems = new ArrayList<>();
        String s[] = getResources().getStringArray(R.array.monitor_func_title_array);
        String index[] = getResources().getStringArray(R.array.monitor_func_index);
        int r[] = {R.mipmap.alarm
                , R.mipmap.monitor_application
                , R.mipmap.monitor_round
                , R.mipmap.monitor_server
                , R.mipmap.monitor_database
                , R.mipmap.monitor_middle_ware
                , R.mipmap.monitor_memory
                , R.mipmap.monitor_internet
                , R.mipmap.monitor_knife_box
                , R.mipmap.monitor_virtualization
                , R.mipmap.monitor_safe
                , R.mipmap.monitor_data_backups};


        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            fi.index = index[i];
            funcItems.add(fi);
        }
    }

    /**
     * 创建点的操作
     * 2016-8-12 下午3:18:15
     */
    private void createDot(int i) {
        dots[i] = new View(getActivity());
        //设置宽高
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
        //设置背景
        dots[i].setBackgroundResource(R.drawable.selector_dot_bg);
        //设置距离右边的距离
        params.rightMargin = 10;
        //将属性设置给控件,使其生效
        dots[i].setLayoutParams(params);//给控件设置属性
        //将创建的点,放到linearlayout中显示
        mLldot.addView(dots[i]);
    }

    /**
     * 切换文本和点
     * 2016-8-12 下午3:09:53
     */
    protected void change(int position) {
        position = position % 2;
        //再次进入的时候,判断是否有白色的点,有变成黑色
        if (currentDot != null) {
            currentDot.setSelected(false);
        }
        //切换点
        dots[position].setSelected(true);//选中点
        //保存白色的点
        currentDot = dots[position];
    }

    private void createGridView() {
        gridView = new MyGridView(getActivity(), new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 4;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return container_gridview.getHeight() / 3;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return container_gridview.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getActivity().getLayoutInflater().inflate(R.layout.monitor_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
                LinearLayout bg = (LinearLayout) view.findViewById(R.id.ll_minitor_bg);
                FuncItem fi = funcItems.get(i);

                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //报警
                    case 0: {
                        startActivity(new Intent(getActivity(), AlarmListActivity.class));
                    }
                    break;
                    //应用系统
                    case 1: {
                        startActivity(new Intent(getActivity(), AppListActivity.class));
                    }
                    break;
                    //动环
                    case 2: {
                        startActivity(new Intent(getActivity(), DhActivity.class));
                    }
                    break;
                    //服务器
                    case 3: {
                        startActivity(new Intent(getActivity(), ServerListActivity.class));
                    }
                    break;
                    //数据库
                    case 4: {
                        startActivity(new Intent(getActivity(), DBListActivity.class));
                    }
                    break;
                    //中间件
                    case 5: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //存储
                    case 6: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //以太网
                    case 7: {
                        startActivity(new Intent(getActivity(), InternetListActivity.class));
                    }
                    break;
                    //刀箱
                    case 8: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //虚拟化
                    case 9: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //安全
                    case 10: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //数据备份
                    case 11: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                    //存储
                    case 12: {
                        normalToasty("暂未开放功能");
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        container_gridview.addView(gridView.getView(), p);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        change(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @OnClick({R.id.service_manager, R.id.custom_service, R.id.operation_quality, R.id.yj_manager})
    public void onClick(View view) {
        switch (view.getId()) {
            //服务管理
            case R.id.service_manager:
                startActivity(new Intent(getActivity(), ITSMActivity.class));
                break;
            //客户服务
            case R.id.custom_service:

                break;
            //运维指标
            case R.id.operation_quality:
                startActivity(new Intent(getActivity(), QuotaActivity.class));
                break;
            //应急管理
            case R.id.yj_manager:

                break;
        }
    }
}
